#include <signal.h>
#include <iostream>

#include <workflow/WFFacilities.h>
#include <workflow/MySQLMessage.h>
#include <workflow/MySQLResult.h>

using namespace std;

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    cout << "sighandler is processing" << endl;
    waitGroup.done();
}

void mysqlCallback(WFMySQLTask * mysqlTask)
{
    cout << "mysqlTask is running" << endl;
    //错误检测
    int state = mysqlTask->get_state();
    int error = mysqlTask->get_error();
    if(state != WFT_STATE_SUCCESS){
        printf("error: %s\n", WFGlobal::get_error_string(state, error));
        return;
    }       
    
    auto resp = mysqlTask->get_resp();
    if(resp->get_packet_type() == MYSQL_PACKET_ERROR) {
        printf("error code %d, %s\n", resp->get_error_code(),
               resp->get_error_msg().c_str());
        return ;
    }

    //处理写操作, 对结果集进行遍历
    protocol::MySQLResultCursor cursor(resp);
    if(cursor.get_cursor_status() == MYSQL_STATUS_OK) {
        printf("OK. %llu rows affected. %d warnings. insert id is %llu\n",
            cursor.get_affected_rows(),
            cursor.get_warnings(),
            cursor.get_insert_id());
    }

}

void test0()
{
    signal(SIGINT, sighandler);
    //创建任务
    string mysqlurl = "mysql://root:1234@localhost:3306";
    auto mysqlTask = WFTaskFactory::create_mysql_task(mysqlurl, 0, mysqlCallback);
    //设置任务的属性
    auto req = mysqlTask->get_req();
    string query("INSERT INTO cloudisk.tbl_user_token(user_name, user_token) values('Jackie', 'token_abcde')");
    req->set_query(query);
    //交给框架来运行
    mysqlTask->start();

    waitGroup.wait();
}


int main()
{
    test0();
    return 0;
}

